package lib.relay;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.Log;

public class RegistRelayFunc {

	// Parent Class Instance
	public static Context _super = null;

	// Main Activity Instance
	public static RegistRelayFunc _this;

	// Relay Info
	public String userIDRelayS;// "Eddy_Hsu@asus.com";
	public String userName;// "Eddy_Hsu@asus.com";
	public String userPasswordRelayS; // "12345678";
	public String servicePortalURLRelayS = "http://aae-spweb.asus.com"; // aae-sgweb001.asus.com";
	public String serviceAreaURLRelayS = "";
	public String strCusid = "";// "59BEADBF-7603-47AD-A11A-06A7E03B34BF";
	public String strUserTicket = "";// "aec6b85303b34215877a512f260c1d68";
	public String strDeviceTicket = "";// "46df8108b7f03d9124062a431";
	public String strDeviceID = "";// "0010010000000000019460";
	public String[] strRelayinfo;
	public String[] strStuninfo;
	public String[] strTurninfo;
	public List<DevListInfo> list = new ArrayList<DevListInfo>();

	public String strCombineRelayinfo = "";
	public String strCombineStuninfo = "";
	public String strCombineTurninfo = "";

	public class SignUpStatus {
		public String status;
		public String content;

		public SignUpStatus() {
			status = "";
			content = "";
		}

		public SignUpStatus(String mStatus, String mConent) {
			this.status = mStatus;
			this.content = mConent;
		}
	}

	public static final String LOGTAG_RELAY_LIB = "LOGTAG_RELAY_LIB";

	public RegistRelayFunc() {
		_this = this;
	}

	public static boolean GetRelaySAuthFunc(Context con, String userId,
			String userPwd) {
		_super = con;
		_this.userIDRelayS = userId;
		_this.userPasswordRelayS = userPwd;
		boolean bValue = _this.GetRelaySAuth();
		return bValue;
	}

	public static SignUpStatus SignUp(Context con, String userId,
			String userPwd, String userName) {
		_super = con;
		_this.userIDRelayS = userId;
		_this.userPasswordRelayS = userPwd;
		_this.userName = userName;
		SignUpStatus bValue = _this.SignUpEmail();
		return bValue;
	}

	public static List<DevListInfo> ListProfileFunc() {
		return _this.GetListProfile();
	}

	public static boolean LogOutRelaySFunc() {
		return _this.LogOutRelayS();
	}

	public static NatCfg SetConfigFunc(NatCfg cfg) {
		if (_this.strDeviceID != "" && _this.strDeviceTicket != "") {
			cfg.device_id = _this.strDeviceID + "@aaerelay.asuscomm.com";
			cfg.device_pwd = _this.strDeviceTicket;
			cfg.sip_srv = _this.strRelayinfo;
			cfg.stun_srv = _this.strStuninfo;
			cfg.turn_srv = _this.strTurninfo;
			cfg.sip_srv_cnt = _this.strRelayinfo.length;
			cfg.stun_srv_cnt = _this.strStuninfo.length;
			cfg.turn_srv_cnt = _this.strTurninfo.length;

			/*
			 * cfg.srv_port_count = CfgDataInit.SRV_PORT_CNT; for(int i = 0;
			 * i<cfg.srv_port_count ;i++){ cfg.natnl_srv_ports[i].lport =
			 * CfgDataInit.LOCAL_PORT[i]; cfg.natnl_srv_ports[i].rport =
			 * CfgDataInit.REMOTE_PORT[i]; }
			 */

		}
		return cfg;
	}

	public static boolean GetKeepAliveFunc() {
		return _this.GetKeepAlive();
	}

	public static boolean UpdateProfileFunc(String strDeviceStatus) {
		return _this.GetUpdateProfile(strDeviceStatus);
	}

	// Functions
	public boolean GetRelaySAuth() {
		return GetAuthorizationRelayS();
	}

	public List<DevListInfo> GetListProfile() {
		GetDeviceList();
		return list;
	}

	public boolean LogOutRelayS() {
		return LogOutRelay();
	}

	public boolean GetKeepAlive() {
		return KeepAlive();
	}

	public boolean GetUpdateProfile(String strDeviceStatus) {
		return UpdateProfile(strDeviceStatus);
	}

	// Functions End------------------------

	// Tool Functions
	// MD5
	private static String MD5(String str) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

		char[] charArray = str.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++) {
			byteArray[i] = (byte) charArray[i];
		}
		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	private String GetMACAddress() {
		String MacAddress = "";
		try {
			WifiManager wifi = (WifiManager) _super
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			String responseMac = info.getMacAddress();

			String[] names = responseMac.split(":");
			for (String name : names) {
				MacAddress += name;
			}

			return MacAddress.toLowerCase();
		} catch (Exception ex) {
			Log.e("GetMACAddress()-----", ex.toString());
		}
		return "";
	}

	private String postDataForRelayServer(String rUrl, String dataStr) {

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httpRequest = new HttpPost(rUrl);
		httpRequest.addHeader("Cookie", "ONE_VER=1_0; path=/; sid=0002");
		HttpResponse httpresponse = null;
		String BackStr = null;

		try {
			if (dataStr != null && dataStr.length() > 0) {
				StringEntity se = new StringEntity(dataStr, HTTP.UTF_8);
				se.setContentType("text/xml");
				httpRequest.setEntity(se);

				httpresponse = httpclient.execute(httpRequest);
				if (httpresponse.getStatusLine().getStatusCode() == 200) {
					BackStr = EntityUtils.toString(httpresponse.getEntity());
					return BackStr;
				} else {
					Log.e("postDataForRelayServer",
							"Write httpresponse Fail!!!!");
				}
			}

		} catch (ClientProtocolException e) {
			Log.e("postDataForRelayServer",
					"ClientProtocal Fail !!!!!!!!!!!!!!");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("postDataForRelayServer", "IOException Fail !!!!!!!!!!!!!!");
			e.printStackTrace();
		} catch (Exception e) {
			Log.e("postDataForRelayServer", "Exception Fail !!!!!!!!!!!!!!");
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}

		return "";
	}

	private void GetDeviceList() {
		if (strCusid == "" || strUserTicket == "" || strDeviceTicket == "") {
			Log.d("GetDeviceList", "strCusid: " + strCusid
					+ ", strUserTicket: " + strUserTicket
					+ ", strDeviceTicket: " + strDeviceTicket);
			return;
		}

		if (list != null && list.size() > 0) {
			for (Iterator<DevListInfo> it = list.iterator(); it.hasNext();) {
				DevListInfo delInfo = (DevListInfo) it.next();
				if (delInfo != null)
					delInfo = null;
			}
			list.clear();
		}

		try {
			// List Profile
			String mXML = "<listprofile><cusid>" + strCusid
					+ "</cusid><userticket>" + strUserTicket
					+ "</userticket><deviceticket>" + strDeviceTicket
					+ "</deviceticket></listprofile>";
			String responseXML = postDataForRelayServer(servicePortalURLRelayS
					+ "/aae/listprofile", mXML);

			// Get Profile List Size
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder ydom = documentBuilderFactory.newDocumentBuilder();
			Document document = ydom.parse(new InputSource(
					new ByteArrayInputStream(responseXML.getBytes("utf-8"))));
			document.getDocumentElement().normalize();
			NodeList xdom = document.getElementsByTagName("listprofile");

			for (int y = 0; y < xdom.getLength(); y++) {

				Element element = (Element) xdom.item(y);
				NodeList childNodes = element.getChildNodes();

				for (int x = 0; x < childNodes.getLength(); x++) {
					Node childNode = childNodes.item(x);
					if (childNode.getNodeType() == Node.ELEMENT_NODE) {
						Element childElement = (Element) childNode;
						if ("status".equals(childElement.getNodeName())) {
							String status = childElement.getFirstChild()
									.getNodeValue();
							if (!status.equals("0")) {
								Log.e("ListProfile",
										"ListProfile Fail!! Status Code:"
												+ status);
								return;
							}
						} else if ("profile".equals(childElement.getNodeName())) {
							NodeList nlData = childElement.getChildNodes();
							DevListInfo data_buf = new DevListInfo();

							for (int z = 0; z < nlData.getLength(); z++) {
								Node data_info = nlData.item(z);

								if (data_info.getNodeType() == Node.ELEMENT_NODE) {
									if ("".equals(data_info.getTextContent())) {
										Log.v("data_info",
												"element content is null");
										continue;
									}
									Element ElementInfo = (Element) data_info;
									if ("deviceid".equals(ElementInfo
											.getNodeName())) {

										data_buf.DEVICE_ID = ElementInfo
												.getFirstChild().getNodeValue();
										Log.d("DeviceId: ", data_buf.DEVICE_ID);
									} else if ("devicestatus"
											.equals(ElementInfo.getNodeName())) {
										data_buf.DEVICE_STATUS = ElementInfo
												.getFirstChild().getNodeValue();
										Log.d("DeviceStatus: ",
												data_buf.DEVICE_STATUS);
									} else if ("devicename".equals(ElementInfo
											.getNodeName())) {
										data_buf.DEVICE_NAME = ElementInfo
												.getFirstChild().getNodeValue();
										Log.d("DeviceName: ",
												data_buf.DEVICE_NAME);
									} else if ("deviceservice"
											.equals(ElementInfo.getNodeName())) {
										// Recording the device service, if
										// current device is not local service.
										// if
										// (!data_buf.DEVICE_ID.equals(strDeviceID))
										{
											data_buf.DEVICE_SERVICE = ElementInfo
													.getFirstChild()
													.getNodeValue();
											Log.d("deviceservice",
													data_buf.DEVICE_SERVICE);
										}
										list.add(data_buf);
									}
								}
							}
							Log.d("ListCount: ", String.valueOf(list.size()));
						}

					}
				}
			}
		} catch (Exception e) {
			Log.e("GetDeviceList", "Exception Fail!!!!!!!!!!");
			e.printStackTrace();
		}
	}

	private boolean GetAuthorizationRelayS() {
		// get getservicearea
		DocumentBuilderFactory documentBuilderFactory = null;
		DocumentBuilder ydom = null;
		Document document = null;
		NodeList xdom = null;

		try {
			// Get the service area URL.
			String mXML = "<?xml version='1.0' encoding='UTF-8'?>\n<getservicearea>\n<userid>"
					+ userIDRelayS
					+ "</userid>\n<passwd>"
					+ userPasswordRelayS
					+ "</passwd>\n</getservicearea>";

			Log.e(LOGTAG_RELAY_LIB,
					"[RegistRelayFunc-GetAuthorizationRelayS] getservicearea url:"
							+ servicePortalURLRelayS + ", xml:" + mXML);

			String responseXML = postDataForRelayServer(servicePortalURLRelayS
					+ "/aae/getservicearea", mXML);
			Log.e(LOGTAG_RELAY_LIB,
					"[RegistRelayFunc-GetAuthorizationRelayS] getservicearea response:"
							+ responseXML);

			// Log.e("JAVA", responseXML);
			try {
				documentBuilderFactory = DocumentBuilderFactory.newInstance();
				ydom = documentBuilderFactory.newDocumentBuilder();
				document = ydom.parse(new InputSource(new ByteArrayInputStream(
						responseXML.getBytes("utf-8"))));
				document.getDocumentElement().normalize();
				xdom = document.getElementsByTagName("getservicearea");

				for (int y = 0; y < xdom.getLength(); y++) {

					Element element = (Element) xdom.item(y);
					NodeList childNodes = element.getChildNodes();

					for (int x = 0; x < childNodes.getLength(); x++) {
						Node childNode = childNodes.item(x);

						if (childNode.getNodeType() == Node.ELEMENT_NODE) {
							Element childElement = (Element) childNode;
							if ("status".equals(childElement.getNodeName())) {
								String status = childElement.getFirstChild()
										.getNodeValue();
								if (!status.equals("0")) {
									Log.e("GetServiceArea",
											"GetSerivceArea Fail!! Status Code: "
													+ status);
									return false;
								}
							} else if ("servicearea".equals(childElement
									.getNodeName())) {
								serviceAreaURLRelayS = childElement
										.getFirstChild().getNodeValue();
								Log.e("test", serviceAreaURLRelayS);
							} else if ("time"
									.equals(childElement.getNodeName())) {
								String str_time = childElement.getFirstChild()
										.getNodeValue();
								Log.e("test", str_time);
							} else
								break;
						}
					}
				}
			} catch (Exception e) {
				Log.e("PARSE", "Parsing XML Fail!!!!!!!!!!!!!!!");
				e.printStackTrace();
				return false;
			}

			if (serviceAreaURLRelayS == "") {
				System.out
						.print("[GetAuthorizationRelayS] serviceAreaURLRelayS is empty, return");
				return false;
			}

			// GetMACAddress
			String strMacAddress = GetMACAddress();
			// string strMacAddress = "002618C06B94";

			if (strMacAddress == "") {
				System.out
						.print("[ASUSWSAgent][GetAuthorizationRelayS] don't find the mac address !!!, return");
				// WritePrivateProfileString("Common", "Authorization", "False",
				// strRelayServerAgentINIPath);
				return false;
			} else
				Log.e("MacAddress", strMacAddress);

			// get local computer name
			String strLocalComputerName = Build.ID;
			Log.e("LocalComName", strLocalComputerName);

			// Login
			String hashedMacAddress = MD5(strMacAddress);
			Log.d("HashedMacAddress", hashedMacAddress);

			mXML = "<?xml version='1.0' encoding='UTF-8'?>\n<login>\n<userid>"
					+ userIDRelayS
					+ "</userid>\n<passwd>"
					+ userPasswordRelayS
					+ "</passwd>\n<devicemd5mac>"
					+ hashedMacAddress
					+ "</devicemd5mac>\n<devicename>"
					+ strLocalComputerName
					+ "</devicename>\n<deviceservice>"
					+ "0002"
					+ "</deviceservice>\n<devicetype>13</devicetype>\n<permission>0</permission>\n</login>";
			// mXML =
			// "<?xml version='1.0' encoding='UTF-8'?>\n<login>\n<userid>" +
			// userIDRelayS + "</userid>\n<passwd>" + userPasswordRelayS +
			// "</passwd>\n<devicemd5mac>" + hashedMacAddress +
			// "</devicemd5mac>\n<devicename>" + strLocalComputerName +
			// "</devicename>\n<deviceservice>"+ "0002" +
			// "</deviceservice>\n<devicetype>13</devicetype>\n<permission>0</permission>\n<devicedesc></devicedesc>\n<devicenat></devicenat>\n</login>";
			// Log.d("XML", mXML);
			Log.e(LOGTAG_RELAY_LIB,
					"[RegistRelayFunc-GetAuthorizationRelayS] login: url:"
							+ servicePortalURLRelayS + ", xml:" + mXML);

			responseXML = postDataForRelayServer(servicePortalURLRelayS
					+ "/aae/login", mXML);

			Log.e(LOGTAG_RELAY_LIB,
					"[RegistRelayFunc-GetAuthorizationRelayS] login response: "
							+ responseXML);

			// Log.d("responseXML", responseXML);

			try {
				documentBuilderFactory = DocumentBuilderFactory.newInstance();
				ydom = documentBuilderFactory.newDocumentBuilder();
				document = ydom.parse(new InputSource(new ByteArrayInputStream(
						responseXML.getBytes("utf-8"))));
				document.getDocumentElement().normalize();
				xdom = document.getElementsByTagName("login");

				int relay_cnt = 0; // for keeping relayinfo_count
				int turn_cnt = 0; // for keeping turninfo_count
				for (int y = 0; y < xdom.getLength(); y++) {

					Element element = (Element) xdom.item(y);
					NodeList childNodes = element.getChildNodes();

					for (int x = 0; x < childNodes.getLength(); x++) {
						Node childNode = childNodes.item(x);
						if (childNode.getNodeType() == Node.ELEMENT_NODE) {
							Element childElement = (Element) childNode;
							if ("status".equals(childElement.getNodeName())) {
								String status = childElement.getFirstChild()
										.getNodeValue();
								if (!status.equals("0")) {
									Log.e("LogIn", "Login Fail!! Status Code:"
											+ status);
									return false;
								}
							} else if ("cusid".equals(childElement
									.getNodeName())) {
								strCusid = childElement.getFirstChild()
										.getNodeValue();
								Log.d("strCusid", strCusid);
							} else if ("userticket".equals(childElement
									.getNodeName())) {
								strUserTicket = childElement.getFirstChild()
										.getNodeValue();
								Log.d("userticket", strUserTicket);
							} else if ("deviceticket".equals(childElement
									.getNodeName())) {
								strDeviceTicket = childElement.getFirstChild()
										.getNodeValue();
								Log.d("deviceticket", strDeviceTicket);
							} else if ("deviceid".equals(childElement
									.getNodeName())) {
								strDeviceID = childElement.getFirstChild()
										.getNodeValue();
								Log.d("deviceid", strDeviceID);
							} else if ("relayinfo".equals(childElement
									.getNodeName())) {
								strCombineRelayinfo = strCombineRelayinfo
										+ childElement.getFirstChild()
												.getNodeValue() + ";";
								Log.d("relayinfo", strCombineRelayinfo);
							} else if ("stuninfo".equals(childElement
									.getNodeName())) {
								strCombineStuninfo = strCombineStuninfo
										+ childElement.getFirstChild()
												.getNodeValue() + ";";
								Log.d("stuninfo", strCombineStuninfo);
							} else if ("turninfo".equals(childElement
									.getNodeName())) {
								strCombineTurninfo = strCombineTurninfo
										+ childElement.getFirstChild()
												.getNodeValue() + ";";
								Log.d("turninfo", strCombineTurninfo);
							}

						}
					}
				}

				strRelayinfo = strCombineRelayinfo.split(";");
				strStuninfo = strCombineStuninfo.split(";");
				strTurninfo = strCombineTurninfo.split(";");

			} catch (Exception e) {
				Log.e("Error", "Please input valid ID and password!");
				ydom = null;
				return false;
			}

			/*
			 * ClientMsg = ""; Message m = myHandler.obtainMessage(); m.what =
			 * WM_GetDeviceList; m.arg1 = 1; myHandler.sendMessage(m);
			 */

			documentBuilderFactory = null;
			document = null;
			ydom = null;
			xdom = null;

		} catch (Exception e) {
			Log.e("GetAuthoriztion", "GetAuthoriztion Fail !!!!!!!!!!!!!!");
			e.printStackTrace();
			return false;
		}
		return true;

	}

	private SignUpStatus SignUpEmail() {
		// get getservicearea
		SignUpStatus result = new SignUpStatus();
		DocumentBuilderFactory documentBuilderFactory = null;
		DocumentBuilder ydom = null;
		Document document = null;
		NodeList xdom = null;

		try {
			// Get the service area URL.
			String mXML = "<?xml version='1.0' encoding='UTF-8'?>\n<registration>\n<userid>"
					+ userIDRelayS
					+ "</userid>\n<passwd>"
					+ userPasswordRelayS
					+ "</passwd>\n"
					+ "<firstname> </firstname>\n"
					+ "<lastname> </lastname>\n"
					+ "<nickname>"
					+ userName
					+ "</nickname>\n"
					+ "<countrycode>USA</countrycode>\n"
					+ "<email>"
					+ userIDRelayS
					+ "</email>\n"
					+ "<ssoflag>0,1</ssoflag>\n"
					+ "<language>tw</language>\n"
					+ "</registration>";

			Log.e(LOGTAG_RELAY_LIB,
					"[RegistRelayFunc-Sign Up] getservicearea url:"
							+ servicePortalURLRelayS + ", xml:" + mXML);

			String responseXML = postDataForRelayServer(servicePortalURLRelayS
					+ "/aae/registration", mXML);
			Log.e(LOGTAG_RELAY_LIB,
					"[RegistRelayFunc-Sign Up] getservicearea response:"
							+ responseXML);

			// Log.e("JAVA", responseXML);
			try {
				documentBuilderFactory = DocumentBuilderFactory.newInstance();
				ydom = documentBuilderFactory.newDocumentBuilder();
				document = ydom.parse(new InputSource(new ByteArrayInputStream(
						responseXML.getBytes("utf-8"))));
				document.getDocumentElement().normalize();
				xdom = document.getElementsByTagName("registration");

				for (int y = 0; y < xdom.getLength(); y++) {

					Element element = (Element) xdom.item(y);
					NodeList childNodes = element.getChildNodes();

					for (int x = 0; x < childNodes.getLength(); x++) {
						Node childNode = childNodes.item(x);

						if (childNode.getNodeType() == Node.ELEMENT_NODE) {
							Element childElement = (Element) childNode;
							if ("status".equals(childElement.getNodeName())) {
								String status = childElement.getFirstChild()
										.getNodeValue();
								result.status = status;
							} else if ("time"
									.equals(childElement.getNodeName())) {
								String str_time = childElement.getFirstChild()
										.getNodeValue();
								Log.e("test", str_time);
							} else if ("errdesc".equals(childElement
									.getNodeName())) {
								String content = childElement.getFirstChild()
										.getNodeValue();
								result.content = content;
							} else
								break;
						}
					}
				}
			} catch (Exception e) {
				Log.e("PARSE", "Parsing XML Fail!!!!!!!!!!!!!!!");
				e.printStackTrace();
				return result;
			}
		} catch (Exception e) {
		}
		return result;
	}

	private boolean LogOutRelay() {
		try {
			// List Profile
			String mXML = "<?xml version='1.0' encoding='UTF-8'?>\n<logout>\n<cusid>"
					+ this.strCusid
					+ "</cusid>\n<deviceid>"
					+ this.strDeviceID
					+ "</deviceid>\n<deviceticket>"
					+ this.strDeviceTicket
					+ "</deviceticket>\n</logout>";
			String responseXML = postDataForRelayServer(servicePortalURLRelayS
					+ "/aae/logout", mXML);
			// Log.d("LogoutXML" , responseXML);

			// Get Profile List Size
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder ydom = documentBuilderFactory.newDocumentBuilder();
			Document document = ydom.parse(new InputSource(
					new ByteArrayInputStream(responseXML.getBytes("utf-8"))));
			document.getDocumentElement().normalize();
			NodeList xdom = document.getElementsByTagName("logout");

			for (int y = 0; y < xdom.getLength(); y++) {

				Element element = (Element) xdom.item(y);
				NodeList childNodes = element.getChildNodes();

				for (int x = 0; x < childNodes.getLength(); x++) {
					Node childNode = childNodes.item(x);
					if (childNode.getNodeType() == Node.ELEMENT_NODE) {
						Element childElement = (Element) childNode;
						if ("status".equals(childElement.getNodeName())) {
							String status = childElement.getFirstChild()
									.getNodeValue();
							if (!status.equals("0")) {
								Log.e("LogOut", "Logout Fail!! Status Code:"
										+ status);
								return false;
							}
						} else if ("time".equals(childElement.getNodeName())) {
							String strtime = childElement.getFirstChild()
									.getNodeValue();
							Log.d("strtime-------------------", strtime);
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	private boolean KeepAlive() {
		try {
			// Keep Alive
			String mXML = "<?xml version='1.0' encoding='UTF-8'?>\n<keepalive>\n<cusid>"
					+ this.strCusid
					+ "</cusid>\n<deviceid>"
					+ this.strDeviceID
					+ "</deviceid>\n<deviceticket>"
					+ this.strDeviceTicket
					+ "</deviceticket>\n</keepalive>";
			String responseXML = postDataForRelayServer(servicePortalURLRelayS
					+ "/aae/keepalive", mXML);

			// Get If Alive
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder ydom = documentBuilderFactory.newDocumentBuilder();
			Document document = ydom.parse(new InputSource(
					new ByteArrayInputStream(responseXML.getBytes("utf-8"))));
			document.getDocumentElement().normalize();
			NodeList xdom = document.getElementsByTagName("keepalive");

			for (int y = 0; y < xdom.getLength(); y++) {

				Element element = (Element) xdom.item(y);
				NodeList childNodes = element.getChildNodes();

				for (int x = 0; x < childNodes.getLength(); x++) {
					Node childNode = childNodes.item(x);
					if (childNode.getNodeType() == Node.ELEMENT_NODE) {
						Element childElement = (Element) childNode;
						if ("status".equals(childElement.getNodeName())) {
							String status = childElement.getFirstChild()
									.getNodeValue();
							Log.e("keep relay alive",
									"keepalive !! Status Code:" + status);
							if (!status.equals("0")) {
								Log.e("keepalive",
										"keepalive Fail!! Status Code:"
												+ status);
								return false;
							}
						} else if ("time".equals(childElement.getNodeName())) {
							String strtime = childElement.getFirstChild()
									.getNodeValue();
							Log.d("strtime-------------------", strtime);
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	private boolean UpdateProfile(String strDeviceStatus) {
		try {
			// Update Profile
			String mXML = "<?xml version='1.0' encoding='UTF-8'?>\n<updateprofile>\n<cusid>"
					+ this.strCusid
					+ "</cusid>\n<deviceid>"
					+ this.strDeviceID
					+ "</deviceid>\n<deviceticket>"
					+ this.strDeviceTicket
					+ "</deviceticket>\n"
					+ "<profile>\n<devicename>"
					+ Build.ID
					+ "</devicename>\n<deviceservice></deviceservice>\n<devicestatus>"
					+ strDeviceStatus
					+ "</devicestatus>\n<permission>0</permission>\n<devicenat></devicenat>\n<devicedesc></devicedesc>\n</profile>\n</updateprofile>";

			String responseXML = postDataForRelayServer(servicePortalURLRelayS
					+ "/aae/updateprofile", mXML);

			// Get is update profile successful?
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder ydom = documentBuilderFactory.newDocumentBuilder();
			Document document = ydom.parse(new InputSource(
					new ByteArrayInputStream(responseXML.getBytes("utf-8"))));
			document.getDocumentElement().normalize();
			NodeList xdom = document.getElementsByTagName("updateprofile");

			for (int y = 0; y < xdom.getLength(); y++) {

				Element element = (Element) xdom.item(y);
				NodeList childNodes = element.getChildNodes();

				for (int x = 0; x < childNodes.getLength(); x++) {
					Node childNode = childNodes.item(x);
					if (childNode.getNodeType() == Node.ELEMENT_NODE) {
						Element childElement = (Element) childNode;
						if ("status".equals(childElement.getNodeName())) {
							String status = childElement.getFirstChild()
									.getNodeValue();
							Log.e("updateprofile",
									"updateprofile Success!! Status Code:"
											+ status);
							if (!status.equals("0")) {
								Log.e("updateprofile",
										"updateprofile Fail!! Status Code:"
												+ status);
								return false;
							}
						} else if ("deviceticketexpiretime".equals(childElement
								.getNodeName())) {
							String expiretime = childElement.getFirstChild()
									.getNodeValue();
							Log.d("deviceticketexpiretime-------------------",
									expiretime);
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

}
